package controllers

import (
	"ScriptServer/models"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

func Login(c *gin.Context){
	username := c.PostForm("username")
	password := c.PostForm("password")
	mid := c.PostForm("mid")
	ip := c.ClientIP()
	result,user := models.ValidUser(username,password)
	if result {
		SigningKey := []byte("xiahaoran")
		claims := models.CustomClaims{
			ip,
			mid,
			jwt.StandardClaims{
				ExpiresAt:time.Now().Add(time.Minute*10).Unix(),
			},
		}
		token := jwt.NewWithClaims(jwt.SigningMethodHS256,claims)
		ss, err := token.SignedString(SigningKey)
		if err!= nil {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"success": false})
		}
		err = user.SaveLoginLog(ss,ip,mid)
		if err != nil{
			c.AbortWithStatusJSON(http.StatusUnauthorized,gin.H{"success": false})
		}
		c.JSON(http.StatusOK, gin.H{"success": true,"token":ss})
		return
	}
	c.AbortWithStatusJSON(http.StatusUnauthorized,gin.H{"success": false})
}